package com.tron.sync.elk;

import com.tron.sync.entities.SyndaOrgDoc;
import com.tron.sync.entities.SyndaUserDoc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;

/**
 * 全文检索初始化程序，检测索引是否存在，如果没存在就创建索引
 */
@Configuration
public class ApplicationInit implements ApplicationRunner {

    Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("elasticSearch start init ...");
        IndexOperations indexOperations1 = elasticsearchRestTemplate.indexOps(SyndaUserDoc.class);
        boolean exists1 = indexOperations1.exists();
        if (!exists1) {
            indexOperations1.create();
            indexOperations1.putMapping(indexOperations1.createMapping(SyndaUserDoc.class));
        }
        IndexOperations indexOperations2 = elasticsearchRestTemplate.indexOps(SyndaOrgDoc.class);
        boolean exists2 = indexOperations2.exists();
        if (!exists2) {
            indexOperations2.create();
            indexOperations2.putMapping(indexOperations2.createMapping(SyndaOrgDoc.class));
        }
        log.info("index is exists elasticSearch init end");
    }
}
